package com.example.shop

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import androidx.paging.PagingData
import androidx.paging.filter
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.base.entity.ProductEntityItem
import com.example.base.mvi.BaseFragment
import com.example.base.mvi.HttpType
import com.example.base.mvi.UiState
import com.example.shop.databinding.FragmentShopBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class ShopFragment : BaseFragment<FragmentShopBinding,ShopIntent,ShopViewModel>() {
    val productPageAdapter by lazy { ProductPageAdapter() }
    lateinit var pagingData: PagingData<ProductEntityItem>
    override fun getLayout(): Int = R.layout.fragment_shop

    override fun getVM(): Class<ShopViewModel> = ShopViewModel::class.java

    override fun initView() {
        binding.rvShop.apply {
            adapter = productPageAdapter
            layoutManager = LinearLayoutManager(context)
        }
        viewModel.sendIntent(ShopIntent.product(5,1))

        productPageAdapter.setOnItemClickListener(object :OnItemClickListener{
            override fun onItemClick(position: Int, item: ProductEntityItem) {
                val id = item.id
                productPageAdapter.submitData(lifecycle,pagingData.filter { it.id!=id })
            }
        })
    }

    override fun initData() {
        lifecycleScope.launch {
            viewModel.uiState.collect{
                when(it){

                    is UiState.onSuccess<*> -> {
                    when(it.type){
                        HttpType.DEFAULT -> {
                            pagingData = it.data as PagingData<ProductEntityItem>
                            productPageAdapter.submitData(pagingData)
                        }
                       /* HttpType.DELETE->{
                            productPageAdapter.submitData(lifecycle,pagingData.filter {
                                it.id!=1
                            })
                        }*/
                        else ->{}
                    }
                    }
                    else->{

                    }
                }
            }
        }
    }

}